package com.example.kotlinlearn.service

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.core.app.NotificationCompat
import com.example.kotlinlearn.MainActivity
import com.example.kotlinlearn.MyApplication
import com.example.kotlinlearn.R

class MyService : Service() {

    private val TAG = "MyService"

    private val mBinder = DownloadBinder()

    class DownloadBinder:Binder(){
        fun startDownload(){
            Toast.makeText(MyApplication.context,"开始下载...",Toast.LENGTH_SHORT).show()
        }
        fun getProgress():Int{
            var random = (Math.random()*10).toInt()
            Toast.makeText(MyApplication.context,"当前进度$random",Toast.LENGTH_SHORT).show()
            return random
        }
    }

    override fun onBind(intent: Intent): IBinder {
        return mBinder
    }

    //服务创建时
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate: 服务被创建")
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            val channel = NotificationChannel("my_service","前天服务通知",
            NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)
        }
        val intent = Intent(this,ServiceActivity::class.java)
        val pi = PendingIntent.getActivity(this,0,intent,0)
        val notification = NotificationCompat.Builder(this,"my_service")
            .setContentTitle("前台服务")
            .setContentText("正在向三体发送信息")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setLargeIcon(BitmapFactory.decodeResource(resources,R.drawable.icon_left))
            .setContentIntent(pi)
            .build()
        //在前台显示通知
        startForeground(1,notification)
    }

    //启动
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onCreate: 服务启动")
        return super.onStartCommand(intent, flags, startId)

    }

    //销毁
    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onCreate: 服务销毁")
    }
}